<template>
  <div class="setRole">
    <el-dialog :title="'为【' + myname + '】分配权限'" :visible="showRole">
      <el-tree
        check-strictly
        ref="mytree"
        :data="roleList"
        show-checkbox
        node-key="id"
        :props="{ label: 'name' }"
        :default-checked-keys="getRight"
        default-expand-all
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button @click="submit" type="primary">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRolesIdApi, setAssignPremApi } from '@/api/roles'
import { getAllPerApi } from '@/api/permission'
export default {
  props: ['myname', 'showRole'],
  data () {
    return {
      roleList: [],
      getRight: [],
      currentId: ''
    }
  },
  created () {
    this.getAllPer()
  },
  methods: {
    async submit () {
      const rightList = this.$refs.mytree.getCheckedKeys()
      await setAssignPremApi({
        id: this.currentId,
        permIds: rightList
      })
      this.$message.success('修改成功')
      this.cancle()
    },
    cancle () {
      this.$emit('update:showRole', false)
    },
    //转换树形结构
    turnData (arr, pid) {
      const res = []
      arr.forEach(item => {
        if (item.pid === pid) {
          const son = this.turnData(arr, item.id)
          if (son.length > 0) {
            item.children = son
          }
          res.push(item)
        }
      })
      return res
    },
    //获得所有树状结构
    async getAllPer () {
      const res = await getAllPerApi()
      //   console.log(res)
      this.roleList = this.turnData(res.data, '0')
    },
    //根据id获取树状结构
    async getRolesId (id) {
      const res = await getRolesIdApi(id)
      // console.log(res)
      this.getRight = res.data.permIds
      this.currentId = id
    }
  }
}
</script>

<style></style>
